<?php
	Header("Content-Type: application/x-javascript");
	session_start();

	$dbh = new mysqli("mysql.planetnorman.net","tc_calendar_user","cmsc345");

	$dbh->select_db("tc_calendar");
	if (mysqli_connect_errno())
	{
		die('Could not connect: ' . mysql_error());
	}

	if(isset($_POST['action'])){
		$response['result'] = true;
		$response['message'] = "Looking good!";	

		$catid = 0;

		$action = $_POST['action'];		
		$title = $_POST['title'];
		$desc = $_POST['desc'];
		$start = $_POST['startyear'] . "-" . 
		$_POST['startmonth'] . "-" .
		$_POST['startday'];
		$end = $_POST['endyear'] . "-" . 
		$_POST['endmonth'] . "-" .
		$_POST['endday'];
	
		if($action === 'create'){
			$dbh->query("insert into events "
			."(cid, owner, subject, description, "
			."readonly, catid) values (1, 1, '$title', '$desc', 0, NULL );");

			$insert_id = $dbh->insert_id;

			$dbh->query("insert into occurrences (eid, startdate, enddate, starttime, endtime, timetype, rid) values ('$insert_id', '$start', '$end', '00:00:00', '23:59:59',  0, 0 );");

		
		}
		else if($action === 'delete'){
			$eid = $_POST['id'];

			$dbh->query("delete from events where eid = $eid;");
			$dbh->query("delete from occurrences where eid = $eid;");

		}
	}
	else{
		$response['result'] = false;	
		$response['message'] = "Feels bad man";
	}

	echo json_encode($response);
?>
